package com.study.happystudy.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.happystudy.tool.ColorChange;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 人脸检测
 * 传入图片File
 * <p>
 * todo: 当前仅供测试,无法实行并发，待pjl经费
 */
@CrossOrigin
@RestController
@RequestMapping("face/")
public class FaceDetectionController {
    // 常量配置
    private static final String apiKey = "agi5M6isVsUx9BWHKZjW99dldAk4-al6";
    private static final String apiSecret = "hDM_ycyC46r8bawpjit7mI6wuM46OSPK";
    private static final HttpPost httpPost = new HttpPost("https://api-cn.faceplusplus.com/facepp/v3/detect");

    @PostMapping("detect")
    public JsonNode detect(@RequestParam MultipartFile imgFile) throws IOException {
        File tempFile = convertMultipartFileToFile(imgFile);
        return detectFaces(apiKey, apiSecret, tempFile);
    }

    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File tempFile = File.createTempFile(Objects.requireNonNull(file.getOriginalFilename()), null);
        file.transferTo(tempFile);
        return tempFile;
    }

    public static JsonNode detectFaces(String apiKey, String apiSecret, File imageFile) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            // 传入常量:
            builder.addPart("api_key", new StringBody(apiKey));
            builder.addPart("api_secret", new StringBody(apiSecret));

            // 传入文件
            builder.addPart("image_file", new FileBody(imageFile));

            // 设置不返回人脸关键点
            builder.addPart("return_landmark", new StringBody("0"));

            // 设置返回人脸属性,性别，年龄，情绪
            builder.addPart("return_attributes", new StringBody("gender,age,emotion,facequality"));

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // toJson

                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = EntityUtils.toString(response.getEntity());
                JsonNode jsonNode = objectMapper.readTree(responseBody);

                // 打印响应状态码
                ColorChange.Blue("Code : " + response.getStatusLine().getStatusCode()+"\n");

                return jsonNode;
            }
        } catch (IOException e) {
            ColorChange.Red("Fuck: " + e.getMessage()+"\n");
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                ColorChange.Red("Fuck: " + e.getMessage()+"\n");
            }
        }

        return null;
    }
}
